/**
 * @author benny.zheng
 * @data 2016-06-06
 * @description 本文件用于方便复制粘贴UI模块之用，请更新这里的说明
 *              另外，考虑到一般是放在js/src/pages/page-name/main.js，因此使用../../
 *              如果不是这个目录，请更改成正确的相对路径
 */
//----------------require--------------

var viewport = require("mlib/dom/viewport"); // viewport
var base = require("mlib/comp/base"); // 基础对象
var parseModule = require("mlib/dom/parseModule"); // 页面模块自动解析
var wechat = require("../plugin/wx/wx-api");

var ajax = require("mlib/io/ajax");
var virtualLink = require("mlib/util/virtualLink");
var closest = require("mlib/dom/closest");
var lazyload = require("mlib/dom/lazyload");
var Confirm = require("../layer/weuiconfirm");
var Alert = require("../layer/weuialert");
var touch = require("mlib/evt/touch");
var Countdown = require("../plugin/util/count-time-down");

var getMeta = require("../plugin/dom/meta");
var listRender = require("./list.ejs");




module.exports = function(node, opts) {
    //-----------声明模块全局变量-------------
    var nodeList = null; // 存储所有关键节点
    var that = base();
    var data = null;
	var metadata =getMeta();
	var searcharr = location.search.match(/unpay=(\d+)/);
	var unpaystr = searcharr ? "&unpay="+searcharr[1] : "";
    var loadobj = null;
    var listelem = null;
    var scrollelem = null;

    //-------------事件响应声明---------------
    var evtFuncs = {
		    getdata:function(pageindex){
				var  url = "/index.php?r=order/list&pageSize=6"+unpaystr+"&ocid="+data.ocId;
					if(that.isLock()) {
						return;
					}
					ajax({
						url:url+"&pageIndex="+pageindex ,
						data: {
							"_csrf":metadata["csrf-token"]
						}, 
						method: "post",
						onSuccess: function(result) {
							that.unLock();
							if(result.length==0 && pageindex==1){
								listelem.insertAdjacentHTML('beforeend','<div class="no-order">您暂时没有订单哦~</div>');
							}else{
								listelem.insertAdjacentHTML('beforeend',listRender({orderlist:result}));
								scrollelem.setAttribute("data-page",parseInt(scrollelem.dataset.page)+1);  
								if(result.length!=0){
								   loadobj.work();  
								}
								result.forEach(function(item){
									if(item.cancelExpireTime!=""){
										new Countdown(document.getElementById("cd-"+item.orderNo),{
											"format": "hh小时mm分ss秒" | "hh:mm:ss", 
											"lastTime": item.cancelCountDown,
											"callback":function(){},
											"complete":function(box){
												var orderitem = closest(box,'.order-item',true);
												var orderbtn = orderitem.querySelector(".order-opt-btn");
												custFuncs.cancelRequest(box.id.slice(3));
												box.parentElement.innerHTML='';		
												orderbtn.innerHTML='';		
											},
										});
									}
								});
								
							}
							 				
						},
						onError: function(xmlHttp) {
						   that.unLock();
						}
					});
			},
			loadlist:function(first){
				if(first){
					evtFuncs.getdata(1);
				}
				loadobj = lazyload(scrollelem,{
					"lazyload" : function(){
						evtFuncs.getdata(scrollelem.dataset.page);
					}
				});
				loadobj.init();
			},
			cancelFn:function(evt){
				  var node = closest(evt.target,"button.cancel"),
					  orderid= node.dataset.oid,ocid=node.dataset.ocid;
					Confirm({content:"\u60a8\u786e\u5b9a\u8981\u53d6\u6d88\u8be5\u8ba2\u5355\uff1f",okFn:function(){
						custFuncs.cancelRequest(orderid,true);							
					}});
			},
			delFn:function(evt){
				  var node = closest(evt.target,"button.del"),
					  orderid= node.dataset.oid,ocid=node.dataset.ocid;
					Confirm({content:"\u5220\u9664\u7684\u8ba2\u5355\u4e0d\u53ef\u6062\u590d\uff0c\u786e\u5b9a\u5220\u9664\uff1f",okFn:function(){
						custFuncs.delRequest(orderid,true);							
					}});
			}
	}

    //-------------子模块实例化---------------
    var initMod = function() { 
        listelem = nodeList.listelem;
        scrollelem = nodeList.scrollelem;
		virtualLink(function(evt){
			location.href = evt.target.getAttribute("data-href");
		});
		wechat('off').init();
    }

    //-------------绑定事件------------------
    var bindEvents = function() {
                touch.on(document.body, 'tap', "button.cancel", evtFuncs.cancelFn);
                touch.on(document.body, 'tap', "button.del", evtFuncs.delFn);
				evtFuncs.loadlist(true);
	}

    //-------------自定义函数----------------
    var custFuncs = {
              getQueryValue:function(key,url){
				  var reg = new RegExp("(^|&|\\?|#)"+ String("unpay").replace(new RegExp("([.*+?^=!:\x24{}()|[\\]\/\\\\])", "g"), '\\\x241') + "=([^&#]*)(&|\x24|#)",""), 
				      match = (url || location.href).match(reg);
					return match ? match[2] : null;
			  },
			  cancelRequest:function(orderid,isAlert){
					if(that.isLock()) {
						return;
					}
					that.lock();
					ajax({
						url: "/index.php?r=order/cancelorder&ocid="+data.ocId+"&orderid="+orderid,
						data: {}, 
						method: "post",
						onSuccess: function(result) {
							that.unLock();
							 if(result.status==1){									
								location.reload(); 
							 }else{
								if(isAlert){
									Alert(result.msg,{
										"okFn":function(){										
												location.reload(); 
										}
									});	
								}
							 }
		
						},
						onError: function(xmlHttp) {
						   that.unLock();
						}
					});
			  },
			  delRequest:function(orderid,isAlert){
					if(that.isLock()) {
						return;
					}
					that.lock();
					ajax({
						url: "/index.php?r=order/delorder&ocid="+data.ocId+"&orderid="+orderid,
						data: {"orderid":orderid}, 
						method: "post",
						onSuccess: function(result) {
							that.unLock();
							 if(result.status==1){									
								location.reload(); 
							 }else{
								if(isAlert){
									Alert(result.msg,{
										"okFn":function(){										
											location.reload(); 
										}
									});	
								}
							 }
		
						},
						onError: function(xmlHttp) {
						   that.unLock();
						}
					});
			  }
    }

    //-------------一切从这开始--------------
    var init = function(_data) {

        data = _data;

        // 找到所有带有node-name的节点
        nodeList = parseModule(node);
        // 子模块实例化
        initMod();
        // 绑定事件
        bindEvents();


    }

    //---------------暴露API----------------
    that.init = init;

    return that;
};